package com.yang.drawcard.application;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.core.utils.dbtutil.DateUtil;
import com.core.utils.dbtutil.DbtLog;
import com.core.utils.dbtutil.FileUtil;
import com.core.utils.exit.ExitAppUtils;

import org.jetbrains.annotations.NotNull;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;


/**
 * 单例的设计模式的异常捕捉
 */

public class ExceptionCrashHandler implements Thread.UncaughtExceptionHandler {

    private static ExceptionCrashHandler mInstance;

    private static final String TAG = "ExceptionCrashHandler:";

    private Thread.UncaughtExceptionHandler mDefaultException;


    public static ExceptionCrashHandler getInstance() {

        if (mInstance == null) {

            //用来解决多线程并发问题

            synchronized (ExceptionCrashHandler.class) {

                mInstance = new ExceptionCrashHandler();

            }

        }

        return mInstance;

    }

    private Context mContext;

    public void init(Context context) {

        this.mContext = context;

        //把全局的异常捕获设置为当前类

        Thread.currentThread().setUncaughtExceptionHandler(this);

        mDefaultException = Thread.getDefaultUncaughtExceptionHandler();

    }

    @Override

    public void uncaughtException(@NotNull Thread thread, @NotNull Throwable ex) {

        //全局异常捕获
        DbtLog.logUtils(TAG, "全局异常捕获:" + getStackTrace(ex));




        //让系统默认处理
        if (!handleExample(ex) && mDefaultException != null) {

            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultException.uncaughtException(thread, ex);

        }
        else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }
            // 退出程序
            /*android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);*/
            //关闭所有的activtys并结束进程
            ExitAppUtils.getInstance().exit();// 自定义方法，关闭当前打开的所有avtivity
            android.os.Process.killProcess(android.os.Process.myPid());
        }




        String st = getStackTrace(ex);
        String sd = "getStackTrace(ex)";

        // jump(st);


    }


    /**
     * 自定义错误处理,收集错误信息 将异常信息保存 发送错误报告等操作均在此完成.
     * <p>
     * 但是无法再访问activity
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */

    private boolean handleExample(Throwable ex) {

        // 如果已经处理过这个Exception,则让系统处理器进行后续关闭处理

        if (ex == null) {

            return false;

        }

        //把crash发送到服务器
        sendCrashToServer(mContext, ex);


        new Thread(() -> {

            // Toast 显示需要出现在一个线程的消息队列中

            Looper.prepare();

            //无法调用dialog，因为它依赖视图

            //            initDialog();

            Toast.makeText(mContext, "很抱歉，程序出现异常，即将退出", Toast.LENGTH_SHORT).show();

            Looper.loop();

        }).start();

        return true;

    }

    private void exitApp() {

        android.os.Process.killProcess(android.os.Process.myPid());

        System.exit(0);

    }

    public static String getStackTrace(Throwable throwable) {

        StringWriter sw = new StringWriter();

        PrintWriter pw = new PrintWriter(sw);


        try {

            throwable.printStackTrace(pw);

            return sw.toString();

        } finally {

            pw.close();

        }

    }

    /**
     * 收集程序崩溃的相关信息
     *
     * @param ctx
     */
    public void sendCrashToServer(Context ctx, Throwable ex) {
        // 崩溃信息集合
        HashMap<String, String> exceptionInfo = new HashMap<String, String>();
        //取出版本号
        PackageManager pm = ctx.getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null": pi.versionName;
                String versionCode = pi.versionCode + "";
                exceptionInfo.put("versionname", versionName); // app版本名称
                exceptionInfo.put("versioncode", versionCode); // app版本号
            }
            // 崩溃信息
            exceptionInfo.put("exceptionsdetail", getStackTrace(ex));
            // Android系统版本(如:4.4.4)
            exceptionInfo.put("androidversion",  android.os.Build.VERSION.RELEASE);
            // 设备型号(如:Google Nexus 7 2013 - 4.4.4 - API 19 - 1200x1920)
            exceptionInfo.put("devicemodel", android.os.Build.MODEL);
            // SDK版本
            exceptionInfo.put("sdkversion", android.os.Build.VERSION.SDK);
            // 崩溃时间
            exceptionInfo.put("crashdate", DateUtil.getDateTimeStr(1));


            final String rquestParam = exceptionInfo.toString();
            // 上传到后台

            String time = DateUtil.formatDate(new Date(), DateUtil.YYYYMMDDHHMMSS);
            String fileName = "crash-" + time  + ".log";

            // DbtLog.e("业代账号",PrefUtils.getString(context,"loginname",""));
            // DbtLog.logUtils(TAG, "业代账号"+PrefUtils.getString(context,"loginname",""));

            // Log.i("业代账号", PrefUtils.getString(context,"loginname",""));

            //String filePath = FileUtil.getSDPath();
            // /storage/emulated/0
            //String SDCARD_DIR = Environment.getExternalStorageDirectory().getPath();

            //String pin = PinYin4jUtil.converterToFirstSpell("与系统中所有的Activity进行交互的类");

            //String yin = PinYin4jUtil.converterToSpell("与系统中所有的Activity进行交互的类");

            FileUtil.writeTxt(rquestParam, FileUtil.getSDPath()+"/"+fileName);

            String adf ="123";
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}